package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据统计业务层
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper ;
    @Autowired
    private UserMapper userMapper ;
    @Autowired
    private WorkspaceService workspaceService ;

    /**
     * 统计营业额数据
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = this.getDateList(begin, end);

        //将列表转换为字符串
        String dateString = StringUtils.join(dateList, ",");

        log.info("日期列表：{}", dateString);
        log.info("开始统计营业额数据...");
        List<Double> turnoverList = new ArrayList<>() ;

        //获取每日一天的消费总金额 而且是已完成订单的总金额
        dateList.forEach(date->{
            //计算这一天的起始日期
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //计算这一天的结束日期
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //统计当天的营业额 select sum(amount) from orders where status = 5 and order_time < endTime and order_time > beginTime
            //这里面没有封装成对象 于是用map集合来传进去这里个参数
            Map map = new HashMap<>() ;
            map.put("begin", beginTime) ;
            map.put("end", endTime) ;
            map.put("status", Orders.COMPLETED) ;
            Double turnover = orderMapper.sumByMap(map) ;
            turnover = turnover == null ? 0.0 : turnover ;
            turnoverList.add(turnover) ;
        });

        log.info("营业额列表：{}" , turnoverList);

        //转换成字符出
        String turnoverString = StringUtils.join(turnoverList, ",");

        //封装响应结果
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .turnoverList(turnoverString)
                .dateList(dateString)
                .build();
        return turnoverReportVO ;
    }

    /**
     * 统计用户数据
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = this.getDateList(begin, end);
        //将列表转换为字符串
        String dateString = StringUtils.join(dateList, ",");
        log.info("日期列表：{}", dateString);

        //当日新增的用户数量 select count(*) from user where create_time < ? and create_time > ?
        List<Integer> newUserList = new ArrayList<>() ;
        //截至当日的总用户数量    select count(*) from user where create_time < ?
        List<Integer> totalUserList = new ArrayList<>() ;
        dateList.forEach(date->{
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map mapForNewUser = new HashMap() ;
            mapForNewUser.put("begin", beginTime) ;
            mapForNewUser.put("end", endTime) ;
            Integer newUser = userMapper.countByMap(mapForNewUser) ;
            newUserList.add(newUser) ;
            Map mapForTotalUser = new HashMap() ;
            mapForTotalUser.put("end" , endTime) ;
            Integer totalUser = userMapper.countByMap(mapForTotalUser) ;
            totalUserList.add(totalUser) ;
        });
        log.info("新增用户列表：{}", newUserList);
        log.info("总用户列表：{}", totalUserList);

        //转字符串
        String newUserString = StringUtils.join(newUserList, ",");
        String totalUserString = StringUtils.join(totalUserList, ",");

        //封装相应结果
        UserReportVO userReportVO = UserReportVO.builder()
                .newUserList(newUserString)
                .totalUserList(totalUserString)
                .dateList(dateString)
                .build();
        return userReportVO ;
    }

    /**
     * 统计订单数据
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //获得日期列表
        List<LocalDate> dateList = this.getDateList(begin, end);
        log.info("日期列表：{}", dateList);

        //生成日期列表字符串
        String dateString = StringUtils.join(dateList, ",");

        log.info("开始计算订单统计数据...");
        List<Integer> orderCountList = new ArrayList<>() ;  //所有订单数量
        List<Integer> validOrderCountList = new ArrayList<>() ; //有效订单数量

        for (LocalDate date : dateList) {//计算开始时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //计算结束时间
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //构造 map
            Map mapForOrder = new HashMap();
            mapForOrder.put("begin", beginTime);
            mapForOrder.put("end", endTime);

            //统计每天的所有订单数量
            Integer totalOrders = orderMapper.countByMap(mapForOrder);
            orderCountList.add(totalOrders) ;

            //构造 map -- 有效订单
            Map mapForValidOrder = new HashMap();
            mapForValidOrder.put("begin", beginTime);
            mapForValidOrder.put("end", endTime);
            mapForValidOrder.put("status", Orders.COMPLETED);

            //统计每天的有效订单数量
            Integer totalValidOrders = orderMapper.countByMap(mapForValidOrder);
            validOrderCountList.add(totalValidOrders) ;
        }

        //转字符串
        String orderCountString = StringUtils.join(orderCountList, ",");
        String validOrderCountString = StringUtils.join(validOrderCountList, ",");

        //统计订单总数
        Map mapForTotalOrder = new HashMap();
        mapForTotalOrder.put("begin" , LocalDateTime.of(begin, LocalTime.MIN)) ;
        mapForTotalOrder.put("end" , LocalDateTime.of(end, LocalTime.MAX)) ;
        Integer orderTotalCount = orderMapper.countByMap(mapForTotalOrder) ;

        //统计有效订单总数
        Map mapForTotalValidOrder = new HashMap();
        mapForTotalValidOrder.put("begin" , LocalDateTime.of(begin, LocalTime.MIN)) ;
        mapForTotalValidOrder.put("end" , LocalDateTime.of(end, LocalTime.MAX)) ;
        mapForTotalValidOrder.put("status" , Orders.COMPLETED) ;
        Integer orderTotalValidCount = orderMapper.countByMap(mapForTotalValidOrder) ;

        //计算订单完成率
        Double orderCompletionRate = orderTotalValidCount.doubleValue() / orderTotalCount.doubleValue() ;

        //封装响应结果
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(dateString)
                .orderCountList(orderCountString)
                .validOrderCountList(validOrderCountString)
                .totalOrderCount(orderTotalCount)
                .validOrderCount(orderTotalValidCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

        return orderReportVO ;
    }

    /**
     * 统计销量排名
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        log.info("开始统计销量排名...");
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN) ;
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX) ;

        //构造 map 对象
        Map map = new HashMap() ;
        map.put("begin" , beginTime) ;
        map.put("end" , endTime) ;
        map.put("type" , Orders.COMPLETED) ;    //只有完成了的订单才有统计意义

        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(map) ;

        //获取名称列表
        List<String> nameList = new ArrayList<>() ;
        //获取数量列表
        List<Integer> numberList = new ArrayList<>() ;
        goodsSalesDTOList.forEach(goodsSalesDTO -> {
            nameList.add(goodsSalesDTO.getName()) ;
            numberList.add(goodsSalesDTO.getNumber()) ;
        }) ;
        log.info("销量排名名称列表：{}", nameList);
        log.info("销量排名数量列表：{}", numberList);

        //封装响应结果
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
        return salesTop10ReportVO ;
    }

    /**
     * 导出运营数据报表
     *
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) throws IOException {
        //通过查询数据库来获取营业数据 --查询近 30 天的营业数据
        //获取 30 天前的那个日期
        LocalDate dateBegin = LocalDate.now().plusDays(-30);
        LocalDate dateEnd = LocalDate.now().plusDays(-1);   //截止到昨天
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //通过POI将数据写入到Excel文件中
        //获取模板文件的输入流
        InputStream resourceAsStream = ReportServiceImpl.class.getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //基于模板文件创建Excel文件
        XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);
        //填充数据--时间
        XSSFSheet sheet = excel.getSheetAt(0);
        //第二行写入时间
        sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

        //填充主要数据
        log.info("开始生成 Excel 文件数据...");
        XSSFRow row = sheet.getRow(3);
        row.getCell(2).setCellValue(businessData.getTurnover()) ;   //营业额
        row.getCell(4).setCellValue(businessData.getOrderCompletionRate()); //订单完成率
        row.getCell(6).setCellValue(businessData.getNewUsers()) ;  //新增用户数
        row = sheet.getRow(4) ;
        row.getCell(2).setCellValue(businessData.getValidOrderCount()) ;    //有效订单数
        row.getCell(4).setCellValue(businessData.getUnitPrice()) ;  //平均客单价

        //填充明细数据
        for (int i = 0 ; i < 30 ; i ++) {
            LocalDate date = dateBegin.plusDays(i); //获取当天的日期
            //查询某一天的营业额数据
            BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

            //动态获取这条数据应该插入的那一行
            row = sheet.getRow(7 + i);

            //填充数据
            row.getCell(1).setCellValue(date.toString());   //日期
            row.getCell(2).setCellValue(data.getTurnover()); //营业额
            row.getCell(3).setCellValue(data.getValidOrderCount()); //有效订单数
            row.getCell(4).setCellValue(data.getOrderCompletionRate()); //订单完成率
            row.getCell(5).setCellValue(data.getUnitPrice());   //平均客单价
            row.getCell(6).setCellValue(data.getNewUsers());    //新增用户数
        }

        //通过输出流来将Excel文件下载到浏览器客户端
        ServletOutputStream outputStream = response.getOutputStream();  //通过输出流对象把Excel文件写回到浏览器
        excel.write(outputStream);

        //关闭资源
        excel.close();
        outputStream.close();
        resourceAsStream.close();
        log.info("导出Excel文件成功！");
    }

    /**
     * 根据起始日期和结束日期计算每一天的日期列表
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getDateList(LocalDate begin , LocalDate end) {
        //计算日期列表字符串
        log.info("开始计算日期列表...");
        //根据起始日期和结束日期计算每一天的连续字符串 用逗号分隔
        List<LocalDate> dateList = new ArrayList<>() ;
        dateList.add(begin) ;
        while(!(begin.equals(end))) {
            begin = begin.plusDays(1) ;
            dateList.add(begin) ;
        }

        return dateList ;
    }
}
